<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" placeholder="请选择归属部门"
                    style="width: 200px;"/>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker clearable
                        v-model="queryParams.startTime"
                        type="datetime"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker clearable
                        v-model="queryParams.endTime"
                        type="datetime"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="学号" prop="stuNo">
        <el-input
          v-model="queryParams.stuNo"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单号" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单名称" prop="orderName">
        <el-input
          v-model="queryParams.orderName"
          placeholder="请输入学号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务单号" prop="outBusinessId">
        <el-input
          v-model="queryParams.outBusinessId"
          placeholder="业务单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="交易状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="交易状态" clearable>
          <el-option
            v-for="dict in dict.type.trade_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-magic-stick"
          size="mini"
          :disabled="multiple"
          @click="handleActivate"
          v-hasPermi="['order:orders:remove']"
        >激活
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-switch-button"
          size="mini"
          :disabled="multiple"
          @click="handleSuspend"
          v-hasPermi="['order:orders:remove']"
        >关闭
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:orders:export']"
        >导出
        </el-button>
      </el-col>
      <el-dropdown :hide-on-click="false" class="top-right-btn">
          <span class="el-dropdown-link">
            <el-button size="mini" icon="el-icon-setting" circle></el-button>
          </span>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item v-for="field in columns" :key="field.key">
            <el-checkbox :value="field.visible" @change="downChange(field.key)">{{ field.label }}</el-checkbox>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="学期年" align="center" prop="semesterYear" min-width="60" v-if="columns[0].visible"/>
      <el-table-column label="学期" align="center" prop="semester" min-width="60" v-if="columns[1].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.semester" :value="scope.row.semester"/>
        </template>
      </el-table-column>
      <el-table-column label="订单号" align="center" prop="id" show-overflow-tooltip width="180" v-if="columns[2].visible"/>
      <el-table-column label="名称" align="center" prop="orderName" show-overflow-tooltip v-if="columns[3].visible"/>
      <el-table-column label="学生" align="center" key="studentName" prop="student.studentName" v-if="columns[4].visible"/>
      <el-table-column label="学号" align="center" key="stuNo" prop="student.stuNo" v-if="columns[16].visible"/>
      <el-table-column label="总价" align="center" prop="totalPrice" v-if="columns[5].visible">
        <template slot-scope="scope">
          {{ scope.row.totalPrice / 100 }}
        </template>
      </el-table-column>
      <el-table-column label="交易状态" align="center" prop="status" v-if="columns[6].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.trade_state" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[7].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="school" show-overflow-tooltip v-if="columns[8].visible"/>
      <el-table-column label="学院" align="center" prop="college" show-overflow-tooltip v-if="columns[9].visible"/>
      <el-table-column label="专业" align="center" prop="major" show-overflow-tooltip v-if="columns[10].visible"/>
      <el-table-column label="年级" align="center" prop="grade" v-if="columns[11].visible"/>
      <el-table-column label="班级" align="center" prop="clazz" v-if="columns[12].visible"/>
      <el-table-column label="订单类型" align="center" prop="orderType" v-if="columns[13].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_order_type" :value="scope.row.orderType"/>
        </template>
      </el-table-column>
      <el-table-column label="缴费项目" align="center" prop="other1" show-overflow-tooltip  v-if="columns[14].visible"/>
      <el-table-column label="账单状态" align="center" prop="other2" v-if="columns[14].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_project_state" :value="scope.row.other2"/>
        </template>
      </el-table-column>
      <el-table-column label="业务订单" align="center" prop="outBusinessId" show-overflow-tooltip  v-if="columns[15].visible"/>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip  v-if="columns[17].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleview(scope.row)"
            v-hasPermi="['order:orders:edit']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['order:orders:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            @click="manualConf(scope.row)"
            v-hasPermi="['order:orders:edit']"
          >核销
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--    修改订单-->
    <el-dialog :title="title" :visible.sync="edit" width="500px" append-to-body>
      <el-form ref="edit" :model="form" label-width="80px">
        <el-form-item label="单价 (元)" prop="totalPrice" required>
          <el-input v-model="priceInYuan" type="text" placeholder="请输入价格"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="hexiao" width="500px" append-to-body>
      <el-form ref="hexiao" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="核销金额" prop="amount" required>
          <el-input v-model="form.amount" placeholder="请输入核销金额"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark" required>
          <el-input v-model="form.remark" placeholder="备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitHeXiao">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer
      :title="title"
      :visible.sync="open"
      size="40%"
      direction="rtl"
      ref="drawer"
      :before-close="handleClose">
      <!--   缴费说明   -->
      <el-descriptions title="缴费说明" :column="1">
        <el-descriptions-item label="账单号" :span="1" v-if="form.id">{{ form.id }}</el-descriptions-item>
        <el-descriptions-item label="缴费项目" v-if="form.orderName" :span="1">{{
            form.orderName
          }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" v-if="form.remark" :span="1">{{
            form.remark
          }}
        </el-descriptions-item>
        <el-descriptions-item :span="1" v-if="form.semester">
          <template slot="label">学期</template>
          <el-tag size="small"> {{ form.semesterYear + "  " + (dict.label.semester[form.semester]) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item v-if="form.totalPrice" :span="1">
          <template slot="label">金额</template>
          <el-tag size="small" type="danger"> {{ form.totalPrice / 100 }}{{ '   ￥' }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <!--   学生信息   -->
      <el-descriptions title="学生信息" :column="1">
        <el-descriptions-item label="姓名" v-if="form.student" :span="1">{{
            form.student.studentName
          }}
        </el-descriptions-item>
        <el-descriptions-item label="学号" v-if="form.student" :span="1">{{ form.student.stuNo }}</el-descriptions-item>
        <el-descriptions-item label="班级" :span="1">
          {{ form.school }}/{{ form.college }}/
          {{ form.major }}/{{ form.clazz }}
        </el-descriptions-item>
      </el-descriptions>
      <!--   缴费项目   -->
      <el-descriptions title="缴费项目" :column="1" v-if="goodItems.length>0">
        <el-descriptions-item  v-for="item in goodItems" :span="1" v-if="item.goodsDetail">
          <template slot="label">{{item.goodsName}}</template>
          <el-tag size="small"> {{ item.goodsPrice / 100}}{{ '   ￥' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label">合计</template>
          <el-tag size="small" type="danger"> {{ form.totalPrice / 100}}{{ '   ￥' }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>
      <!--   支付记录TODO   -->
      <h3>支付记录</h3>
      <el-table :data="recordList" >
        <el-table-column type="index" width="55" align="center"/>
        <el-table-column align="center" prop="createTime"/>
        <el-table-column align="center" prop="totalPrice" >
          <template slot-scope="scope">
            {{ scope.row.totalPrice / 100 }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.trade_state" :value="scope.row.status"/>
          </template>
        </el-table-column>
      </el-table>
      <!--   退款记录TODO   -->
    </el-drawer>
  </div>
</template>

<script>
import {listOrders, getOrders, updateOrders, manualConf, changeStatus} from "@/api/order/orders";
import {deptSchoolTreeSelect} from "@/api/campus/Org";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listRecord} from "@/api/order/record";

export default {
  name: "Orders",
  components: {Treeselect},
  dicts: ['sys_normal_disable', 'semester', 'trade_state','pay_order_type','payment_project_state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 部门树选项
      deptOptions: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单信息表格数据
      ordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      edit: false,
      hexiao: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        totalPrice: null,
        createDate: null,
        startTime: null,
        endTime: null,
        status: null,
        userId: null,
        stuNo: null,
        studentName: null,
        orderType: null,
        orderName: null,
        orderDescrip: null,
        orderDetail: null,
        outBusinessId: null
      },
      // 表单参数
      form: {},
      recordList:[],
      goodItems: [],
      // 表单校验
      rules: {
        totalPrice: [
          {required: true, message: "总价不能为空", trigger: "blur"}
        ],
        priceInYuan: [
          {required: true, message: '请输入价格', trigger: 'blur'},
          {
            pattern: /^\d{0,8}(\.\d{0,2})?$/,
            message: '请输入有效的价格（最多8位整数和2位小数）',
            trigger: ['blur', 'change']
          }
        ],
        createDate: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        status: [
          {required: true, message: "交易状态不能为空", trigger: "change"}
        ],
        userId: [
          {required: true, message: "用户id不能为空", trigger: "blur"}
        ],
        orderType: [
          {required: true, message: "订单类型不能为空", trigger: "change"}
        ],
        orderDescrip: [
          {required: true, message: "订单描述不能为空", trigger: "blur"}
        ],
        orderDetail: [
          {required: true, message: "订单明细json不能为空", trigger: "blur"}
        ],
        outBusinessId: [
          {required: true, message: "外部系统业务id不能为空", trigger: "blur"}
        ],
        amount: [
          {required: true, message: "核销金额不能为空", trigger: "blur"}
        ]
      },
      // 列信息
      columns: [
        {key: 0, label: `学期年`, prop: 'semesterYear', visible: true},
        {key: 1, label: `学期`, prop: 'semester', visible: true},
        {key: 2, label: `订单号`, prop: 'id', visible: true},
        {key: 3, label: `名称`, prop: 'orderName', visible: false},
        {key: 4, label: `学生`, prop: 'studentName', visible: true},
        {key: 5, label: `总价`, prop: 'totalPrice', visible: true},
        {key: 6, label: `交易状态`, prop: 'status', visible: true},
        {key: 7, label: `创建时间`, prop: 'createTime', visible: true},
        {key: 8, label: `学校`, prop: 'school', visible: false},
        {key: 9, label: `学院`, prop: 'college', visible: false},
        {key: 10, label: `专业`, prop: 'major', visible: false},
        {key: 11, label: `年级`, prop: 'grade', visible: false},
        {key: 12, label: `班级`, prop: 'clazz', visible: false},
        {key: 13, label: `订单类型`, prop: 'orderType', visible: false},
        {key: 14, label: `缴费项目`, prop: 'other1', visible: true},
        {key: 15, label: `业务订单`, prop: 'outBusinessId', visible: false},
        {key: 16, label: `学号`, prop: 'stuNo', visible: true},
        {key: 17, label: `备注`, prop: 'remark', visible: false},
      ],
    };
  },
  computed: {
    // 以元为单位的价格，用于表单展示和输入
    priceInYuan: {
      get() {
        return (this.form.totalPrice / 100).toFixed(2);
      },
      set(value) {
        this.form.totalPrice = Math.round(value * 100);
      }
    }
  },
  created() {
    this.getDeptTree();
    this.getList();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptSchoolTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询订单信息列表 */
    getList() {
      this.loading = true;
      listOrders(this.queryParams).then(response => {
        this.ordersList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.edit = false;
      this.hexiao = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        totalPrice: null,
        createDate: null,
        status: null,
        userId: null,
        orderType: null,
        orderName: null,
        orderDescrip: null,
        orderDetail: null,
        outBusinessId: null,
        amount: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单信息";
    },
    handleview(row) {
      this.reset();
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data;
        if (row.orderType==="SPECIAL"){
          this.goodItems = [];
        }else if(row.orderType==="UNIQUE"){
          this.goodItems = JSON.parse(response.data.orderDetail) || [];
        }
        this.open = true;
        this.title = "缴费账单信息";
      });
      listRecord({orderId:id}).then(response => {
        this.recordList = response.rows;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data;
        if (response.data.status === "NOTPAY") {
          this.edit = true;
          this.title = "修改订单信息";
        } else {
          this.$modal.msgError("该订单已被学生确认，进入处理状态，无法修改！");
        }

      });
    },
    /** 核销订单 */
    manualConf(row) {
      this.reset();
      const id = row.id || this.ids
      getOrders(id).then(response => {
        this.form = response.data;
        if (response.data.status === "NOTPAY") {
          this.hexiao = true;
          this.title = "修改订单信息";
        } else {
          this.$modal.msgError("该订单已被确认，不满足核销！");
        }

      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["edit"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.edit = false;
              this.getList();
            });
          } else {
            // addOrders(this.student).then(response => {
            //   this.$modal.msgSuccess("新增成功");
            //   this.open = false;
            //   this.getList();
            // });
          }
        }
      });
    },
    submitHeXiao() {
      this.$refs["hexiao"].validate(valid => {
        if (valid) {
          if (this.form.id != null && this.hexiao) {
            manualConf(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.hexiao = false;
              this.getList();
            });
          } else {
            this.$modal.msgError("核销失败！");
          }
        }
      });
    },
    /** 关闭操作 */
    handleSuspend(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认关闭账单[' + ids + ']？').then(function () {
        return changeStatus(ids[0],1);
      }).then(() => {
        this.getList();
        this.$modal.msgWarning("成功关闭！");
      }).catch(() => {
      });
    },
    /** 激活操作 */
    handleActivate(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认关闭账单[' + ids + ']？').then(function () {
        return changeStatus(ids[0],2);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("成功激活");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('order/orders/export', {
        ...this.queryParams
      }, `orders_${new Date().getTime()}.xlsx`)
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    downChange(val) {
      const column = this.columns.find(col => col.key === val);
      if (column) {
        column.visible = !column.visible;
      }
    }
  }
};
</script>
<style>
.demo-drawer__footer {
  display: flex;
  margin-left: 10px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.demo-drawer__footer button {
  flex: 1
}
</style>
